from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from users.models import User


class OAuthQQUserSerializer(serializers.Serializer):
    """
    QQ登录用户绑定的序列化器
    """
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label="手机号", regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)

    def validate(self, data):

        # 检验access_token
        access_token = data['access_token']

        openid = OAuthQQ.check_bind_user_access_token(access_token)
        if not openid:
            raise serializers.ValidationError("无效的access_token")

        data['openid'] = openid

        # 检验短信验证码
        mobile = data['mobile']
        sms_code = data['sms_code']

        redis_conn = get_redis_connection('verify_code')
        redis_sms_code = redis_conn.get("sms_%s" % mobile)
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("验证码输入错误")

        # 如果用户存在，检查用户密码
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 用户不存在
            pass
        else:
            password = data['password']
            if not user.check_password(password):
                raise serializers.ValidationError("密码输入错误")
            data['user'] = user

        return data

    def create(self, validated_data):
        """
        保存绑定用户
        :param validated_data:
        :return:
        """
        user = validated_data.get('user', None)

        if not user:
            # 用户不存在
            # 这的cerate_user() 是django 用模型类 提供的, 只能保存用户名,手机号和密码
            user = User.objects.cerate_user(
                username=validated_data['mobile'],
                mobile=validated_data['mobile'],
                password=validated_data['password']
            )

        # 保存到qq用户和商城用户的关系表
        OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )

        return user
